package com.Exception异常;

import java.util.Scanner;

/**
 * 作    者 ：吾路巴尼
 * 创建时间 ：2025/2/16-17:35
 */
public class 常见的运行时异常 {
    /**
     * 1. NullPointerException 空指针异常
     * 2. ArrayIndexOutOfBoundsException 数组下标越界异常
     * 3. ClassCastException 类型转换异常
     * 4. NumberFormatException 数字格式化异常
     * 5. ArithmeticException 算术异常
     *//***/
    static Scanner  sc = new Scanner(System.in);
    public static void main(String[] args) {
        /**1. NullPointerException 空指针异常*/
        String str = null;
        try{
        System.out.println(str.length());} //str为空的时候，获取长度会报空指针异常
        catch (Exception e){
            System.out.println("1. "+e.getMessage());
        }


        /**2. ArrayIndexOutOfBoundsException 数组下标越界异常*/
        try{
            int[] arr = new int[3];
            arr[99] = 10;  //数组下标越界
        }catch (Exception e){
            System.out.println("2. "+e.getMessage());
        }

        /**3. ClassCastException 类型转换异常*/
        try{
            Object obj = new String("hello"); //向上转型
            String string = (String)obj;  //向下转型
            Integer in = (Integer)obj;  //将String类强转成Integer类，类型转换异常
        }catch (Exception e){
            System.out.println("3. "+e.getMessage());
        }

        /** 4. NumberFormatException 数字格式化异常*/

        try {
            String name = "hello";
            int i = Integer.parseInt(name);  //将字符串hello转换为整数，数字格式化异常
        } catch (NumberFormatException e) {
            System.out.println("4. "+e.getMessage());
        }

        /**5.ArithmeticException 算术异常*/
        try{
            int i = 10/0;  //除数不能为0
        }catch (Exception e){
            System.out.println("5. "+e.getMessage());
        }
    }
}
